package com.xykj.enterprise.wechat.base.config;

import com.xykj.enterprise.wechat.base.exception.AppException;
import com.xykj.enterprise.wechat.base.exception.TokenExpiredException;
import com.xykj.enterprise.wechat.base.exception.UnauthorizedException;
import com.xykj.enterprise.wechat.base.web.domain.AjaxData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Feng Chen
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler({Exception.class})
    public AjaxData handle(Exception e) {
        logger.error("", e);
        if (e instanceof UnauthorizedException) {
            UnauthorizedException ue = (UnauthorizedException) e;
            return AjaxData.failure(ue.getErrCode(), ue.getErrMsg());
        } else if (e instanceof TokenExpiredException) {
            TokenExpiredException ue = (TokenExpiredException) e;
            return AjaxData.failure(ue.getErrCode(), ue.getErrMsg());
        } else if (e instanceof AppException) {
            AppException ue = (AppException) e;
            return AjaxData.failure(ue.getErrCode(), ue.getErrMsg());
        }
        return AjaxData.failure();
    }

}
